package com.supermap.qdsearch.activity;

import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.supermap.android.maps.BoundingBox;
import com.supermap.android.maps.CoordinateReferenceSystem;
import com.supermap.android.maps.DefaultItemizedOverlay;
import com.supermap.android.maps.LineOverlay;
import com.supermap.android.maps.MBTilesLayerView;
import com.supermap.android.maps.MapController;
import com.supermap.android.maps.MapView;
import com.supermap.android.maps.Overlay;
import com.supermap.android.maps.OverlayItem;
import com.supermap.android.maps.Point2D;
import com.supermap.android.maps.PointOverlay;
import com.supermap.android.maps.PolygonOverlay;
import com.supermap.qdsearch.R;
import com.supermap.qdsearch.adapter.MyAdapter;
import com.supermap.qdsearch.app.SearchApp;
import com.supermap.qdsearch.entity.CollectBean;
import com.supermap.qdsearch.entity.InspectionBean;
import com.supermap.qdsearch.entity.InspectionServerEntity;
import com.supermap.qdsearch.entity.MapEntity;
import com.supermap.qdsearch.fragment.CheckFragment;
import com.supermap.qdsearch.fragment.CollectListFragment;
import com.supermap.qdsearch.fragment.RepairFragment;
import com.supermap.qdsearch.fragment.SettingFragment;
import com.supermap.qdsearch.fragment.SyncFragment;
import com.supermap.qdsearch.fragment.VerifyFragment;
import com.supermap.qdsearch.utils.LocationService;
import com.supermap.qdsearch.utils.LocationUtils;
import com.supermap.qdsearch.utils.LogUtils;
import com.supermap.qdsearch.utils.TimeUtils;
import com.supermap.qdsearch.utils.ToastUtils;
import com.supermap.qdsearch.widget.CustomPopWindow;
import com.supermap.qdsearch.widget.CustomProgressBar;
import com.yanzhenjie.alertdialog.AlertDialog;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements CollectListFragment.OnAddCollect {


    @BindView(R.id.nav_view)
    NavigationView navigationView;

    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;

    @BindView(R.id.fl_front)
    FrameLayout flFront;
    @BindView(R.id.ib_setting)
    RadioButton ibSetting;
    @BindView(R.id.ib_sync)
    RadioButton ibSync;
    @BindView(R.id.ib_location)
    RadioButton ibLocation;
    @BindView(R.id.ib_clean)
    RadioButton ibClean;
    @BindView(R.id.ib_full)
    RadioButton ibFull;
    @BindView(R.id.cr_change_map)
    RadioButton crChangeMap;
    @BindView(R.id.rb_collection)
    RadioButton rbCollection;
    @BindView(R.id.rb_inspection)
    RadioButton rbInspection;
    @BindView(R.id.tv_inspection)
    TextView tvInspection;
    @BindView(R.id.fl_inspection)
    FrameLayout flInspection;
    @BindView(R.id.rb_service_task)
    RadioButton rbServiceTask;
    @BindView(R.id.tv_service_task)
    TextView tvServiceTask;
    @BindView(R.id.fl_service_task)
    FrameLayout flServiceTask;
    @BindView(R.id.rb_verification)
    RadioButton rbVerification;
    @BindView(R.id.tv_verification)
    TextView tvVerification;
    @BindView(R.id.fl_verification)
    FrameLayout flVerification;
    @BindView(R.id.group_task)
    RadioGroup groupTask;
    @BindView(R.id.map_view)
    MapView mapView;


    private Fragment fragment;

    private String getMapsUrl;
    private List<MapEntity> list;

    private String rest;
    private String base;
    private CoordinateReferenceSystem crs;

    private LocationService locationService;
    private CustomProgressBar dialog;


    // 存放绘制线或面的点集合
    private List<Point2D> geoPoints = new ArrayList<Point2D>(1);
    private List<PointOverlay> pointOverlays = new ArrayList<PointOverlay>(1);
    // 存放所需绘制的线对象集合
    private List<LineOverlay> lineOverlays = new ArrayList<LineOverlay>(1);
    // 默认的绘制线对象
    // private LineOverlay firstLineOverlay;
    // 存放所需绘制的面对象集合
    private List<PolygonOverlay> polygonOverlays = new ArrayList<PolygonOverlay>(1);
    // 默认的绘制面对象
    // private PolygonOverlay firstPolygonOverlay;
    // 触屏Overlay,用来获取点坐标
    private TouchOverlay touchOverlay;
    // 绘制要素状态
    private int drawStatic = 1;// 1代表绘制线，2表示绘制面，0代表绘制点
    // 单个绘制对象绘制完成的标志
    private boolean addOverlayOver = false;
    private boolean useDraw = true;
    private static final int README_DIALOG = 9;
    // 触屏的x坐标
    private int touchX;

    // 触屏的y坐标
    private int touchY;

    // private long previousTouchTime = 0;
    // private boolean isDoubleTouch = false;
//    private boolean isMove = false;
    private boolean isMultiTouch = false;


    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     *
     */
    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {

                updateShow(location);
            }
        }

    };
    private MBTilesLayerView mbTilesLayerView2;
    private MBTilesLayerView mbTilesLayerView3;
    private MBTilesLayerView mbTilesLayerView4;
    private MBTilesLayerView mbTilesLayerView1;
    private CustomPopWindow customPopWindow;

    private void startLocation() {
        // -----------location config ------------
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        list = new ArrayList<>();
        getMapsUrl = getResources().getString(R.string.get_maps_url);
        rest = getResources().getString(R.string.map_rest_url);
        base = getResources().getString(R.string.map_base_url);

        //初始化加载弹框
        dialog = new CustomProgressBar(this);
        dialog.show();

        //初始化百度地图服务
        locationService = ((SearchApp) (getApplication())).locationService;
        locationService.stop();
        //初始化toolbal和navigationview
        initToolBar();

        //初始化地图
        initMap();

        //初始化地图上的点线面
        initMapRes();

        //初始化触屏overlay
        touchOverlay = new TouchOverlay();

    }


    /**
     * 初始化toolbal和navigationview
     */
    public void initToolBar() {


        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                drawerLayout.closeDrawer(navigationView);

                return true;
            }
        });
    }


    //初始化map
    public void initMap() {
        addFristLayer();
    }


    /**
     * 初始化第一层图层
     */
    public void addFristLayer() {

        //构造离线图层，Mbtiles文件所在的路径相对于移动端设备sdcard的路径
        mbTilesLayerView1 = new MBTilesLayerView(this, Environment.getExternalStorageDirectory().getPath() + "/shenzhen/T2Firstfloor.smtiles");
        mbTilesLayerView2 = new MBTilesLayerView(this, Environment.getExternalStorageDirectory().getPath() + "/shenzhen/T2Secondfloor.smtiles");
        mbTilesLayerView3 = new MBTilesLayerView(this, Environment.getExternalStorageDirectory().getPath() + "/shenzhen/T2Thirdfloor.smtiles");
        mbTilesLayerView4 = new MBTilesLayerView(this, Environment.getExternalStorageDirectory().getPath() + "/shenzhen/T2Fourthfloor.smtiles");
        //添加离线图层
        mapView.addLayer(mbTilesLayerView1);
        //启用内置的缩放控件

        mapView.setBuiltInZoomControls(false);
        mapView.setClickable(true);
        mapView.addMapViewEventListener(new MapViewEventAdapter());
        dialog.dismiss();
    }


    /**
     * 初始化资源标注
     */
    public void initMapRes(){
        /**
         113.301030,23.400735
         113.300476,23.399936
         113.301479,23.400093
         113.301955,23.400633
         113.300405,23.400975
         113.299927,23.400381
         113.300003,23.399927
         113.300355,23.399584
         */

        List<InspectionServerEntity> outList = new ArrayList<>();
        // 0正常 1待维修 2待认证
        CollectBean collectBean1 = new CollectBean("001", "消火栓", "0", "T2航站楼", "2", "1", "113.301030", "23.400735");
        CollectBean collectBean2 = new CollectBean("002", "光缆", "1", "T2航站楼", "2", "2", "113.300476,113.300003", "23.399936,23.400975");
        CollectBean collectBean3 = new CollectBean("003", "电梯面", "2", "T2航站楼", "2", "0", "113.299927,113.300003,113.300355", "23.400381,23.399927,23.399584");
        ArrayList<InspectionBean> inspectionBeans1 = new ArrayList<>();
        ArrayList<InspectionBean> inspectionBeans2 = new ArrayList<>();
        ArrayList<InspectionBean> inspectionBeans3 = new ArrayList<>();
        InspectionBean bean1 = new InspectionBean("001", "001", "灭火去不能使用", "", "", TimeUtils.date2String(new Date()));
        InspectionBean bean2 = new InspectionBean("001", "001", "正常", "", "", TimeUtils.date2String(new Date()));
        inspectionBeans1.add(bean1);
        inspectionBeans1.add(bean2);
        InspectionBean bean3 = new InspectionBean("001", "002", "正常", "", "", TimeUtils.date2String(new Date()));
        InspectionBean bean4 = new InspectionBean("001", "002", "光缆内线暴露", "已修复,请领导检查", "", TimeUtils.date2String(new Date()));
        inspectionBeans2.add(bean3);
        inspectionBeans2.add(bean4);
        InspectionBean bean5 = new InspectionBean("001", "003", "电梯不正常", "已修复,请领导检查", "验证通过", TimeUtils.date2String(new Date()));
        InspectionBean bean6 = new InspectionBean("001", "003", "正常", "", "", TimeUtils.date2String(new Date()));
        inspectionBeans3.add(bean5);
        inspectionBeans3.add(bean6);

        outList.add(new InspectionServerEntity(collectBean1,inspectionBeans1));
        outList.add(new InspectionServerEntity(collectBean2,inspectionBeans2));
        outList.add(new InspectionServerEntity(collectBean3,inspectionBeans3));

        for (InspectionServerEntity entity:outList){
            CollectBean collectBean = entity.getCollectBean();
            if("0".equals(collectBean.getResType())){
                String longitude = collectBean.getLongitude();
                String latitude = collectBean.getLatitude();
                //添加点
                Point2D point2D = new Point2D(Double.parseDouble(longitude), Double.parseDouble(latitude));
                PointOverlay pointOverlay = new PointOverlay(point2D, MainActivity.this);
                pointOverlay.setTouchEventListener(new Overlay.OverlayTouchEventListener() {
                    @Override
                    public void onTouch(MotionEvent motionEvent, MapView mapView) {
                        LogUtils.d(motionEvent.getAction());
                    }

                    @Override
                    public void onTouch(MotionEvent motionEvent, Overlay overlay, MapView mapView) {
                        LogUtils.d(motionEvent.getAction());
                        if(customPopWindow!=null){
                            customPopWindow.dissmiss();
                        }
                        CustomPopWindow.PopupWindowBuilder popupWindowBuilder = new CustomPopWindow.PopupWindowBuilder(MainActivity.this);
                        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_feature_info, null);
                        customPopWindow = popupWindowBuilder.enableOutsideTouchableDissmiss(true).enableBackgroundDark(true).setView(view).create();
                        customPopWindow.showAtLocation(mapView,Gravity.CENTER,0,0);
                        view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                customPopWindow.dissmiss();
                            }
                        });
                        ListView listView =  view.findViewById(R.id.listview);
                        listView.setAdapter(new MyAdapter<InspectionBean>(entity.getList(),R.layout.pop_feature_info_item) {
                            @Override
                            public void bindView(ViewHolder holder, InspectionBean obj) {
                                holder.setText(R.id.tv_build,collectBean.getBuild());
                                holder.setText(R.id.tv_floor,collectBean.getFloor());
                                holder.setText(R.id.res_name,collectBean.getResName());
                                holder.setText(R.id.tv_hisotry,obj.getCreateDate());
                                holder.setText(R.id.tv_describe,obj.getProblemDesc());
                            }
                        });
                    }
                });
                mapView.getOverlays().add(pointOverlay);
            }else if("1".equals(collectBean.getResType())){
                List<Point2D> point2DS = new ArrayList<Point2D>();
                String longitude = collectBean.getLongitude();
                String latitude = collectBean.getLatitude();
                String[] longitudes = longitude.split(",");
                String[] latitudes = latitude.split(",");
                for(int i=0;i<longitudes.length;i++){
                    longitude = longitudes[i];
                    latitude = latitudes[i];
                    Point2D point2D = new Point2D(Double.parseDouble(longitude), Double.parseDouble(latitude));
                    point2DS.add(point2D);
                }
                //添加线
                LineOverlay lineOverlay = new LineOverlay(getLinePaint());
                lineOverlay.setData(point2DS);
                lineOverlay.setTouchEventListener(new Overlay.OverlayTouchEventListener() {
                    @Override
                    public void onTouch(MotionEvent motionEvent, MapView mapView) {
                        LogUtils.d(motionEvent.getAction());
                    }

                    @Override
                    public void onTouch(MotionEvent motionEvent, Overlay overlay, MapView mapView) {
                        if(customPopWindow!=null){
                            customPopWindow.dissmiss();
                        }
                        CustomPopWindow.PopupWindowBuilder popupWindowBuilder = new CustomPopWindow.PopupWindowBuilder(MainActivity.this);
                        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_feature_info, null);
                        customPopWindow = popupWindowBuilder.enableOutsideTouchableDissmiss(true).enableBackgroundDark(true).setView(view).create();
                        customPopWindow.showAtLocation(mapView,Gravity.CENTER,0,0);
                        view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                customPopWindow.dissmiss();
                            }
                        });
                       ListView listView =  view.findViewById(R.id.listview);
                       listView.setAdapter(new MyAdapter<InspectionBean>(entity.getList(),R.layout.pop_feature_info_item) {
                           @Override
                           public void bindView(ViewHolder holder, InspectionBean obj) {
                                holder.setText(R.id.tv_build,collectBean.getBuild());
                                holder.setText(R.id.tv_floor,collectBean.getFloor());
                                holder.setText(R.id.res_name,collectBean.getResName());
                                holder.setText(R.id.tv_hisotry,obj.getCreateDate());
                                holder.setText(R.id.tv_describe,obj.getProblemDesc());
                           }
                       });

                    }
                });
                mapView.getOverlays().add(lineOverlay);
            }else if("2".equals(collectBean.getResType())){
                List<Point2D> point2DS = new ArrayList<Point2D>();
                String longitude = collectBean.getLongitude();
                String latitude = collectBean.getLatitude();
                String[] longitudes = longitude.split(",");
                String[] latitudes = latitude.split(",");
                for(int i=0;i<longitudes.length;i++){
                    longitude = longitudes[i];
                    latitude = latitudes[i];
                    Point2D point2D = new Point2D(Double.parseDouble(longitude), Double.parseDouble(latitude));
                    point2DS.add(point2D);
                }
                //添加面
                PolygonOverlay polygonOverlay = new PolygonOverlay(getPolygonPaint());
                polygonOverlay.setData(point2DS);
                polygonOverlay.setTouchEventListener(new Overlay.OverlayTouchEventListener() {
                    @Override
                    public void onTouch(MotionEvent motionEvent, MapView mapView) {
                        LogUtils.d(motionEvent.getAction());
                    }

                    @Override
                    public void onTouch(MotionEvent motionEvent, Overlay overlay, MapView mapView) {
                        if(customPopWindow!=null){
                            customPopWindow.dissmiss();
                        }
                        CustomPopWindow.PopupWindowBuilder popupWindowBuilder = new CustomPopWindow.PopupWindowBuilder(MainActivity.this);
                        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_feature_info, null);
                        customPopWindow = popupWindowBuilder.enableOutsideTouchableDissmiss(true).enableBackgroundDark(false).setView(view).create();
                        customPopWindow.showAtLocation(mapView,Gravity.CENTER,0,0);
                        view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                customPopWindow.dissmiss();
                            }
                        });
                        ListView listView =  view.findViewById(R.id.listview);
                        listView.setAdapter(new MyAdapter<InspectionBean>(entity.getList(),R.layout.pop_feature_info_item) {
                            @Override
                            public void bindView(ViewHolder holder, InspectionBean obj) {
                                holder.setText(R.id.tv_build,collectBean.getBuild());
                                holder.setText(R.id.tv_floor,collectBean.getFloor());
                                holder.setText(R.id.res_name,collectBean.getResName());
                                holder.setText(R.id.tv_hisotry,obj.getCreateDate());
                                holder.setText(R.id.tv_describe,obj.getProblemDesc());
                            }
                        });

                    }
                });
                mapView.getOverlays().add(polygonOverlay);
            }
        }

    }

    /**
     * 画出GPS图标
     */
    public void drawGps(BDLocation location) {

        double x = location.getLongitude();
        double y = location.getLatitude();
        Drawable drawableBlue = getResources().getDrawable(R.mipmap.location_checked);
        DefaultItemizedOverlay overlay = new DefaultItemizedOverlay(drawableBlue);
        OverlayItem overlayItem2 = new OverlayItem(new Point2D(x, y), "", "");
        overlay.addItem(overlayItem2);
        mapView.getOverlays().add(overlay);
        Point2D point2D = new Point2D(x, y);
        MapController controller = mapView.getController();
        controller.setCenter(point2D);
        controller.setZoom(10);

        // 重新onDraw一次
        mapView.invalidate();
    }


    //定义一个更新显示的方法
    private void updateShow(BDLocation location) {
        double x = location.getLongitude();
        double y = location.getLatitude();
        BoundingBox bounds = mapView.getBounds();
        boolean contains = bounds.contains(new Point2D(x, y));
        if(contains){
            drawGps(location);
            String addrStr = location.getAddrStr();
            ToastUtils.showShortToast(addrStr);
        }else{
            ToastUtils.showShortToast("您不在地图范围内！");
        }

    }


    long lasttime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (System.currentTimeMillis() - lasttime <= 2000) {

                AlertDialog.Builder builder = AlertDialog.newBuilder(MainActivity.this);
                AlertDialog dialog = builder.setTitle("温馨提示").setMessage("您确定要退出应用吗？").setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Process.killProcess(Process.myPid());
                        System.exit(0);
                    }
                }).setCancelable(true).show();
            } else {
                ToastUtils.showShortToast("再次点击，将退出应用！");
                lasttime = System.currentTimeMillis();
            }


        }
        return true;
    }

    /**
     * 点击事件
     * @param view
     */
    @OnClick({R.id.ib_setting, R.id.ib_sync, R.id.ib_location, R.id.ib_clean, R.id.ib_full, R.id.cr_change_map, R.id.rb_collection, R.id.rb_inspection, R.id.rb_service_task, R.id.rb_verification})
    public void onViewClicked(View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        switch (view.getId()) {
            case R.id.ib_setting:
                fragment = new SettingFragment();
                fragmentManager.beginTransaction().addToBackStack(null).replace(R.id.fl_front, fragment).commit();
                break;
            case R.id.ib_sync:
                fragment = new SyncFragment();
                fragmentManager.beginTransaction().addToBackStack(null).replace(R.id.fl_front, fragment).commit();
                break;
            case R.id.ib_location:
                if (fragment != null)
                    fragmentManager.beginTransaction().remove(fragment).commit();
                if (!LocationUtils.isGpsEnabled()) {
                    ToastUtils.showShortToast("请打开GPS~");
                    LocationUtils.openGpsSettings();
                } else {
                    startLocation();
                }
                break;
            case R.id.ib_clean:
                if (fragment != null)
                    fragmentManager.beginTransaction().remove(fragment).commit();
                break;
            case R.id.ib_full:
                if (fragment != null)
                    fragmentManager.beginTransaction().remove(fragment).commit();
                mapView.getController().setZoom(0);
                mapView.invalidate();
                break;
            case R.id.cr_change_map:
                if (fragment != null)
                    fragmentManager.beginTransaction().remove(fragment).commit();

                View inflate = LayoutInflater.from(this).inflate(R.layout.fragment_map_switch, null);
                CustomPopWindow customPopWindow = new CustomPopWindow.PopupWindowBuilder(this).setView(inflate).enableBackgroundDark(true).setOutsideTouchable(false).create();
                customPopWindow.showAtLocation(mapView, Gravity.CENTER, 0, 0);
                RadioGroup radioGroup = inflate.findViewById(R.id.group_floor);
                radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        customPopWindow.dissmiss();
                        mapView.getOverlays().clear();
                        initMapRes();
                        switch (checkedId){
                            case R.id.first:
                                mapView.removeAllLayers();
                                mapView.addLayer(mbTilesLayerView1);
                                mapView.invalidate();
                                break;
                            case R.id.two:
                                mapView.removeAllLayers();
                                mapView.addLayer(mbTilesLayerView2);
                                mapView.invalidate();
                                break;
                            case R.id.three:
                                mapView.removeAllLayers();
                                mapView.addLayer(mbTilesLayerView3);
                                mapView.invalidate();
                                break;
                            case R.id.four:
                                mapView.removeAllLayers();
                                mapView.addLayer(mbTilesLayerView4);
                                mapView.invalidate();
                                break;
                        }
                    }
                });
                break;
            case R.id.rb_collection:
                this.fragment = new CollectListFragment();
                fragmentManager.beginTransaction().addToBackStack(null).replace(R.id.fl_front, fragment).commit();
                break;
            case R.id.rb_inspection:
                this.fragment = new CheckFragment();
                fragmentManager.beginTransaction().addToBackStack(null).replace(R.id.fl_front, this.fragment).commit();
                break;
            case R.id.rb_service_task:
                this.fragment = new RepairFragment();
                fragmentManager.beginTransaction().addToBackStack(null).replace(R.id.fl_front, this.fragment).commit();
                break;
            case R.id.rb_verification:
                this.fragment = new VerifyFragment();
                fragmentManager.beginTransaction().addToBackStack(null).replace(R.id.fl_front, this.fragment).commit();
                break;
        }


    }

    /**
     * 资源采集
     */
    public void addCollect() {

        mapView.getOverlays().removeAll(pointOverlays);
        mapView.getOverlays().removeAll(lineOverlays);
        mapView.getOverlays().removeAll(polygonOverlays);
        mapView.setUseDoubleTapEvent(true);
        useDraw = true;
        pointOverlays.clear();
        polygonOverlays.clear();
        geoPoints.clear();
        lineOverlays.clear();
        isOnLongTouch=false;

        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_res_type, null);
        CustomPopWindow customPopWindow = new CustomPopWindow.PopupWindowBuilder(this).setView(inflate).enableBackgroundDark(true).setOutsideTouchable(false).create();
        customPopWindow.showAtLocation(mapView, Gravity.CENTER, 0, 0);
        inflate.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RadioGroup radioGroup = inflate.findViewById(R.id.rg_type);
                int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
                if (checkedRadioButtonId == -1) {
                    ToastUtils.showShortToast("请选择采集类型");
                    return;
                } else {
                    customPopWindow.dissmiss();
                }
                switch (checkedRadioButtonId) {
                    case R.id.dian:
                        // 添加PointOverlay绘点，地图刷新
                        geoPoints.clear();
                        if (!mapView.getOverlays().contains(touchOverlay)) {
                            mapView.getOverlays().add(touchOverlay);
                        }
                        drawStatic = 0;
                        // 不启用双击事件触发放大地图
                        mapView.setUseDoubleTapEvent(false);
                        break;
                    case R.id.xian:
                        // 添加LineOverlay绘线，地图刷新
                        geoPoints.clear();
                        if (!mapView.getOverlays().contains(touchOverlay)) {
                            mapView.getOverlays().add(touchOverlay);
                        }
                        addLineOverLayer();
                        drawStatic = 1;
                        mapView.setUseDoubleTapEvent(false);
                        break;
                    case R.id.mian:
                        // 添加PolygonOverlay绘面，地图刷新
                        geoPoints.clear();
                        if (!mapView.getOverlays().contains(touchOverlay)) {
                            mapView.getOverlays().add(touchOverlay);
                        }
                        addPolygonOverLayer();
                        drawStatic = 2;
                        mapView.setUseDoubleTapEvent(false);
                        break;
                }


            }
        });

        inflate.findViewById(R.id.btn_return).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customPopWindow.dissmiss();
            }
        });
        inflate.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customPopWindow.dissmiss();
            }
        });

    }


    /**
     * 添加面标注
     */
    private void addPolygonOverLayer() {
        PolygonOverlay polygonOverlay = new PolygonOverlay(getPolygonPaint());
        mapView.getOverlays().add(polygonOverlay);
        polygonOverlays.add(polygonOverlay);
    }

    /**
     * 添加线标注
     */
    private void addLineOverLayer() {
        LineOverlay lineOverlay = new LineOverlay(getLinePaint());
        mapView.getOverlays().add(lineOverlay);
        lineOverlays.add(lineOverlay);
    }


    /**
     * 绘线风格
     *
     * @return
     */
    public static Paint getLinePaint() {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.argb(200, 10, 230, 250));
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setAntiAlias(true);
        return paint;

    }

    /**
     * 绘面风格
     *
     * @return
     */
    public static Paint getPolygonPaint() {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.argb(200, 10, 230, 250));
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setStrokeWidth(2);
        paint.setAntiAlias(true);
        return paint;

    }


    /**
     * 给Overlay设置点集合，开始绘制对象，并刷新地图
     *
     * @param overlay
     * @param gps
     */
    private void setOverlayData(Overlay overlay, List<Point2D> gps) {
        if (overlay == null) {
            return;
        }
        List<Point2D> geoPointList = new ArrayList<Point2D>();
        if (gps != null && gps.size() > 0) {
            copyList(gps, geoPointList);
        } else if (geoPoints.size() > 0) {
            copyList(geoPoints, geoPointList);
        }
        if (geoPointList.size() > 0) {
            if (overlay instanceof LineOverlay) {
                ((LineOverlay) overlay).setData(geoPointList);
            } else if (overlay instanceof PolygonOverlay) {
                ((PolygonOverlay) overlay).setData(geoPointList);
            }
            mapView.invalidate();
        }
    }

    /**
     * list复制
     * @param sourcegps
     * @param targetgps
     */
    private void copyList(List<Point2D> sourcegps, List<Point2D> targetgps) {
        for (int i = 0; i < sourcegps.size(); i++) {
            targetgps.add(new Point2D(sourcegps.get(i)));
        }
    }

    /**
     * 设置标注的数据
     * @param overlay
     */
    private void setOverlayData(Overlay overlay) {
        setOverlayData(overlay, null);
    }

    /**
     * 触屏Overlay
     */
    class TouchOverlay extends Overlay {
        private List<Point> movePoints = new ArrayList<Point>();

        @Override
        public boolean onTouchEvent(MotionEvent event, final MapView mapView) {
            if (useDraw) {
                if (event.getPointerCount() > 1) {// 发生多点触碰
                    isMultiTouch = true;
                }

                if(isOnLongTouch){
                    return false;
                }


                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (movePoints.size() > 1) {// 如果发生平移，不绘制
                        double distance = 0;
                        for (int i = movePoints.size() - 1; i > 0; i--) {
                            double ds = Math.pow((movePoints.get(i).x - movePoints.get(i - 1).x), 2)
                                    + Math.pow((movePoints.get(i).y - movePoints.get(i - 1).y), 2);
                            if (ds > distance) {
                                distance = ds;
                            }
                        }
                        if (distance > 16) {
                            return false;
                        }
                    }
                    if (isMultiTouch) {// 如果发生多点触碰，不绘制
                        isMultiTouch = false;
                        return false;
                    }
                    // if(isDoubleTouch){//如果发生双击，只绘制第一次的点
                    // isDoubleTouch = false;
                    // return true;
                    // }
                    touchX = Math.round(event.getX());
                    touchY = Math.round(event.getY());
                    // 记录点击位置
                    Point2D touchGeoPoint = mapView.getProjection().fromPixels(touchX, touchY);

                    // 当addOverlayOver为true时，当前对象绘制结束，根据绘制状态，选择创建新的绘制对象加入绘制对象集合中，并置 addOverlayOver为false
                    if (addOverlayOver) {
                        // Log.i("iserver", "onTouchEvent");
                        if (drawStatic == 1) {
                            LineOverlay lineOverlay = new LineOverlay(getLinePaint());
                            mapView.getOverlays().add(lineOverlay);
                            // Log.i("iserver", "lineOverlays前个数：" + lineOverlays.size());
                            lineOverlays.add(lineOverlay);
                            // Log.i("iserver", "lineOverlays后个数：" + lineOverlays.size());
                        } else if (drawStatic == 2) {
                            PolygonOverlay polygonOverlay = new PolygonOverlay(getPolygonPaint());
                            mapView.getOverlays().add(polygonOverlay);
                            polygonOverlays.add(polygonOverlay);
                        }
                        geoPoints.clear();
                        addOverlayOver = false;
                    }

                    if (drawStatic == 1 || drawStatic == 2) {
                        if (!geoPoints.contains(touchGeoPoint)) {
                            // Log.i("iserver", "touchGeoPoint");
                            geoPoints.add(touchGeoPoint);
                        }
                    }

                    if (drawStatic == 0) {// 0代表绘制点
                        mapView.getOverlays().removeAll(pointOverlays);
                        mapView.getOverlays().removeAll(lineOverlays);
                        mapView.getOverlays().removeAll(polygonOverlays);
                        Log.e("onTouch", ">>>>>>>>>>>>>>>>>>>>>>onTouch<<<<<<<<<<<<<<<<<<<<<<<");
                        if (!mapView.getOverlays().contains(touchOverlay)) {
                            mapView.getOverlays().add(touchOverlay);
                        }
                        PointOverlay pointOverlay = new PointOverlay(touchGeoPoint, MainActivity.this);
                        mapView.getOverlays().add(pointOverlay);
                        geoPoints.clear();
                        geoPoints.add(touchGeoPoint);
                        pointOverlays.add(pointOverlay);
                        mapView.invalidate();
                    }

                    if (drawStatic == 1) {// 1代表绘制线
                        setOverlayData(lineOverlays.get(lineOverlays.size() - 1));
                        // mapView.invalidate();
                    } else if (drawStatic == 2) {// 2表示绘制面
                        setOverlayData(polygonOverlays.get(polygonOverlays.size() - 1));
                        //mapView.invalidate();
                    }
                } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    movePoints.clear();
                } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    movePoints.add(new Point(Math.round(event.getX()), Math.round(event.getY())));
                }
            }
            return false;
        }
    }

    /**
     * MapView事件处理适配器，提供长按事件的实现
     */
    private boolean isOnLongTouch = false;

    class MapViewEventAdapter implements MapView.MapViewEventListener {

        private View view;
        private CustomPopWindow inspectionPopWindow;

        @Override
        public void moveStart(MapView paramMapView) {

        }

        @Override
        public void move(MapView paramMapView) {

        }

        @Override
        public void moveEnd(MapView paramMapView) {

        }

        @Override
        public void touch(MapView paramMapView) {

        }

        @Override
        public void longTouch(MapView paramMapView) {
            Log.i("iserver", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>longTouch<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
            //防止
            if (geoPoints.isEmpty() && lineOverlays.isEmpty() && polygonOverlays.isEmpty()) {
                return;
            }
            isOnLongTouch=true;

            //以 长按事件 作为绘制当前线面对象结束的标志
            if (drawStatic == 1 || drawStatic == 2) {
                addOverlayOver = true;
                mapView.setUseDoubleTapEvent(false);
                useDraw = false;
            }
            view = LayoutInflater.from(MainActivity.this).inflate(R.layout.window_collection_detail, null);

            CustomPopWindow.PopupWindowBuilder popupWindowBuilder = new CustomPopWindow.PopupWindowBuilder(MainActivity.this);
            inspectionPopWindow = popupWindowBuilder.setView(view).enableOutsideTouchableDissmiss(true).enableBackgroundDark(true).create();
            inspectionPopWindow.showAtLocation(mapView, Gravity.BOTTOM, 0, 0);
            view.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EditText editText = view.findViewById(R.id.et_build);
                    EditText editFloor = view.findViewById(R.id.et_floor);
                    EditText editDept = view.findViewById(R.id.et_dept);
                    EditText editResName = view.findViewById(R.id.et_resname);
                    Spinner spinner = view.findViewById(R.id.sp_res_type);
                    EditText editRemark = view.findViewById(R.id.et_remark);
                    String resType = spinner.getSelectedItem().toString();
                    String build = editText.toString();
                    String floor = editFloor.toString();
                    String dept = editDept.toString();
                    String resName = editResName.toString();
                    String remark = editRemark.toString();
                    ToastUtils.showShortToast("采集成功~");
                }
            });
            view.findViewById(R.id.ib_close).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (inspectionPopWindow != null) {
                        inspectionPopWindow.dissmiss();
                    }
                    mapView.getOverlays().removeAll(pointOverlays);
                    mapView.getOverlays().removeAll(lineOverlays);
                    mapView.getOverlays().removeAll(polygonOverlays);
                    mapView.setUseDoubleTapEvent(false);
                    mapView.invalidate();
                    useDraw = false;
                    pointOverlays.clear();
                    polygonOverlays.clear();
                    geoPoints.clear();
                    lineOverlays.clear();
                    isOnLongTouch=false;
                }
            });
        }

        @Override
        public void zoomStart(MapView paramMapView) {

        }

        @Override
        public void zoomEnd(MapView paramMapView) {

        }

        @Override
        public void mapLoaded(MapView paramMapView) {

        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (locationService != null) {
            locationService.unregisterListener(mListener);
            locationService.stop();
        }
    }
}